package org.shj.spring.boot.lang.util;

import com.esotericsoftware.reflectasm.MethodAccess;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Table;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.*;
import java.util.List;
import java.util.Map;

/**
 * 反射工具类.
 * <p>
 * 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
 */
public class ReflectionUtil {

    private static Logger log = LoggerFactory.getLogger(ReflectionUtil.class);

    public static final String CGLIB_CLASS_SEPARATOR = "$$";
    public static final Class[] NO_PARAM_SIGNATURE = new Class[0];
    public static final Object[] NO_PARAMS = new Object[0];

    public static final Class[] SINGLE_OBJECT_PARAM_SIGNATURE = new Class[]{Object.class};

    private transient static Map<Class, MethodAccess> methodAccessCache = Maps.newHashMap();
    private static Table<Class, String, Field> classStringFieldTable = HashBasedTable.create();


    private ReflectionUtil() {
    }

    /**
     * 调用Getter方法.
     */
    public static Object invokeGetter(Object obj, String propertyName) {
        String getterMethodName = "get" + StringUtils.capitalize(propertyName);
        return invokeMethod(obj, getterMethodName, new Class[]{}, new Object[]{});
    }

    /**
     * 调用Setter方法.使用value的Class来查找Setter方法.
     */
    public static void invokeSetter(Object obj, String propertyName, Object value) {
        invokeSetter(obj, propertyName, value, null);
    }

    /**
     * 调用Setter方法.
     *
     * @param propertyType 用于查找Setter方法,为空时使用value的Class替代.
     */
    public static void invokeSetter(Object obj, String propertyName, Object value, Class<?> propertyType) {
        Class<?> type = propertyType != null ? propertyType : value.getClass();
        String setterMethodName = "set" + StringUtils.capitalize(propertyName);
        invokeMethod(obj, setterMethodName, new Class[]{type}, new Object[]{value});
    }

    /**
     * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
     */
    public static Object getFieldValue(final Object obj, final String fieldName) throws IllegalArgumentException {
        Field field = getAccessibleField(obj, fieldName);

        if (field == null) {
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
        }

        Object result = null;
        try {
            result = field.get(obj);
        } catch (IllegalAccessException e) {
            log.error("不可能抛出的异常{}", e.getMessage());
        }
        return result;
    }

    /**
     * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
     */
    public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
        Field field = getAccessibleField(obj, fieldName);

        if (field == null) {
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
        }

        try {
            field.set(obj, value);
        } catch (IllegalAccessException e) {
            log.error("不可能抛出的异常:{}", e.getMessage());
        }
    }

    public static void setFieldValueSilent(final Object obj, final String fieldName, final Object value) {
        Field field = getAccessibleField(obj, fieldName);
        if (field != null) {
            try {
                field.set(obj, value);
            } catch (IllegalAccessException e) {
                log.error("不可能抛出的异常:{}", e.getMessage());
            }
        }
    }

    /**
     * 对于被cglib AOP过的对象, 取得真实的Class类型.
     */
    public static Class<?> getUserClass(Object instance) {
        if (instance == null) {
            return null;
        }
        Class clazz = instance.getClass();
        if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
            Class<?> superClass = clazz.getSuperclass();
            if (superClass != null && !Object.class.equals(superClass)) {
                return superClass;
            }
        }
        return clazz;
    }

    /**
     * 直接调用对象方法, 无视private/protected修饰符.
     * 用于一次性调用的情况.
     */
    public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,
                                      final Object[] args) {
        Method method = getAccessibleMethod(obj, methodName, parameterTypes);
        if (method == null) {
            throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
        }

        try {
            return method.invoke(obj, args);
        } catch (Exception e) {
            throw convertReflectionExceptionToUnchecked(e);
        }
    }

    public static Map<String, Object> unpackageFields(MethodAccess methodAccess, Object obj) {
        Map<String, Object> map = Maps.newHashMap();
        for (String methodName : methodAccess.getMethodNames()) {
            if (StringUtils.startsWith(methodName, "get")) {
                String field = StringUtils.uncapitalize(StringUtils.removeStart(methodName, "get"));
                Object value = null;
                try {
                    value = methodAccess.invoke(obj, methodName);
                } catch (Exception e) {
                }
                if (value != null) {
                    map.put(field, value);
                }
            }
        }
        return map;
    }

    public static Map<String, Object> unpackageFields(Object obj) {
        MethodAccess methodAccess = getMethodAccess(obj.getClass());
        return unpackageFields(methodAccess, obj);
    }

    public static MethodAccess getMethodAccess(Class entityClass) {
        MethodAccess methodAccess;
        if (methodAccessCache.containsKey(entityClass)) {
            methodAccess = methodAccessCache.get(entityClass);
        } else {
            methodAccess = MethodAccess.get(entityClass);
            methodAccessCache.put(entityClass, methodAccess);
        }
        return methodAccess;
    }

    /**
     * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
     * <p>
     * 如向上转型到Object仍无法找到, 返回null.
     */
    public static Field getAccessibleField(final Object obj, final String fieldName) {
        Validate.notNull(obj, "object can't be null");
        return getAccessibleField(obj.getClass(), fieldName);
    }

    public static Field getAccessibleField(final Class clazz, final String fieldName) {
        Validate.notNull(clazz, "object can't be null");
        Validate.notBlank(fieldName, "fieldName can't be blank");
        Field field = classStringFieldTable.get(clazz, fieldName);
        if (field == null) {
            for (Class<?> superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
                try {
                    field = superClass.getDeclaredField(fieldName);
                    field.setAccessible(true);
                    classStringFieldTable.put(clazz, fieldName, field);
                } catch (NoSuchFieldException e) {//NOSONAR
                    // Field不在当前类定义,继续向上转型
                }
            }
        }

        return field;
    }

    /**
     * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
     * 如向上转型到Object仍无法找到, 返回null.
     * <p>
     * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
     */
    public static Method getAccessibleMethod(final Object obj, final String methodName,
                                             final Class<?>... parameterTypes) {
        Validate.notNull(obj, "object can't be null");

        for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                Method method = superClass.getDeclaredMethod(methodName, parameterTypes);

                method.setAccessible(true);

                return method;

            } catch (NoSuchMethodException e) {//NOSONAR
                // Method不在当前类定义,继续向上转型
            }
        }
        return null;
    }

    /**
     * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
     * 如无法找到, 返回Object.class.
     * eg.
     * public UserDao extends HibernateDao<User>
     *
     * @param clazz The class to introspect
     * @return the first generic declaration, or Object.class if cannot be determined
     */
    public static <T> Class<T> getSuperClassGenricType(final Class clazz) {
        return getSuperClassGenricType(clazz, 0);
    }

    /**
     * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
     * 如无法找到, 返回Object.class.
     * <p>
     * 如public UserDao extends HibernateDao<User,Long>
     *
     * @param clazz service The class to introspect
     * @param index the Index of the generic ddeclaration,logStart from 0.
     * @return the index generic declaration, or Object.class if cannot be determined
     */
    public static Class getSuperClassGenricType(final Class clazz, final int index) {

        Type genType = clazz.getGenericSuperclass();

        if (!(genType instanceof ParameterizedType)) {
            log.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
            return Object.class;
        }

        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

        if (index >= params.length || index < 0) {
            log.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
                    + params.length);
            return Object.class;
        }
        if (!(params[index] instanceof Class)) {
            log.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
            return Object.class;
        }

        return (Class) params[index];
    }

    /**
     * 将反射时的checked exception转换为unchecked exception.
     */
    public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
        if (e instanceof RuntimeException) {
            return (RuntimeException) e;
        }
        if (e instanceof IllegalAccessException
                || e instanceof NoSuchMethodException) {
            return new IllegalArgumentException(e);
        }
        if (e instanceof InvocationTargetException) {
            return new RuntimeException(((InvocationTargetException) e).getTargetException());
        }
        return new RuntimeException("Unexpected Checked Exception.", e);
    }

    public static Type[] getSuperClassGenricTypes(Class clazz) {
        Type typeClass = clazz.getGenericSuperclass();
        if (typeClass instanceof ParameterizedType) {
            return ((ParameterizedType) typeClass).getActualTypeArguments();
        } else {
            return null;
        }
    }

    public static List<Field> getAccessibleFields(Class clazz, Class annotationClass) {
        Validate.notNull(clazz, "object can't be null");
        Validate.notNull(annotationClass, "annotationClass can't be blank");
        List<Field> fields = Lists.newArrayList();
        for (Class<?> superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
            Field[] superClassFields = superClass.getDeclaredFields();
            for (Field field : superClassFields) {
                if (field.getAnnotation(annotationClass) != null) {
                    fields.add(field);
                    field.setAccessible(true);
                }
            }
        }

        return fields;
    }
}

